package com.tansun.tandata.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tansun.tandata.common.TandataServerEnum;
import com.tansun.tandata.entity.LogInfoErro;
import com.tansun.tandata.entity.RaiseNum;
import com.tansun.tandata.feign.SysFeignService;
import com.tansun.tandata.service.RaisNumService;
import com.tansun.tandata.utils.Constants;
import com.tansun.tandata.utils.JsonUtil;
import com.tansun.tandata.utils.ParentController;
import com.tansun.tandata.utils.ResponseBase;
import com.tansun.tandata.vo.LdapUser;
import com.tansun.tandata.vo.req.RaiseNumPageVO;
import com.tansun.tandata.vo.req.RaiseNumVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 提数记录控制器

 * @CreateDate 20200426
 * @author liuyu
 * @Version v1.0
 *
 */
@Api(value = "提数管理接口")
@RestController
@RequestMapping(value = "/tishu/RaiseNum")
public class RaisNumController extends ParentController {

    @Autowired
    private RaisNumService raisNumService;
    @Autowired
    private SysFeignService sysFeignService;

    @RequestMapping(value="testCon",method= RequestMethod.GET)
    public String testCon(){
        return "testOK";
    }


    @ApiOperation(value="查询提数记录列表", notes="查询提数记录列表")
    @RequestMapping(value = "/getRaiseNumList", method = RequestMethod.POST)
    public ResponseBase getRaiseNumList(@Valid @RequestBody RaiseNumPageVO raiseNumPageVO) {
        Map<String, Object> data = new HashMap<>();
        try {
            Page<Object> pageInfo = PageHelper.startPage(raiseNumPageVO.getPage(), raiseNumPageVO.getLimit(), true);
            List<RaiseNum> raiseNumList =raisNumService.getRaiseNumList(raiseNumPageVO);
            data.put("total", pageInfo.getTotal());
            data.put("data", raiseNumList);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/getRaiseNumList");
            log.setParamStr(JsonUtil.toJsonObjectString(raiseNumPageVO));
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
        }
        return setResultSuccess(data);
    }

    @ApiOperation(value="新建提数记录", notes="提数记录基本信息插入")
    @RequestMapping(value = "/saveRaisNum", method = RequestMethod.POST)
    public ResponseBase saveRaisNum(@Valid @RequestBody RaiseNumVO raiseNumVO, BindingResult bindingResult ) {
        // 验证实体输入参数
        ResponseBase validResult = validateField(bindingResult);
        if (validResult != null) {
            return validResult;
        }
        try {
            int result= raisNumService.addRaisNum(raiseNumVO);
            if(-2==result){
                //延时提数时预计开始时间超过了当前时间
                return setResult(Constants.RAIS_NUM_ERRO_2, localeMessage.getMessage("tishu.raisnum.error.beginTimeOvertime"), null);
            }
            if(-3==result){
                //调用提数脚本调用失败
                return setResult(Constants.RAIS_NUM_ERRO_3, localeMessage.getMessage("tishu.raisnum.error.execRaisShellErro"), null);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/saveRaisNum");
            log.setParamStr(JsonUtil.toJsonObjectString(raiseNumVO));
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess(raiseNumVO);
    }

    @ApiOperation(value="编辑提数记录", notes="提数记录基本信息插入")
    @RequestMapping(value = "/editRaisNum", method = RequestMethod.POST)
    public ResponseBase editRaisNum(@Valid @RequestBody RaiseNumVO raiseNumVO, BindingResult bindingResult ) {
        try {
            int result= raisNumService.upDateRaisNum(raiseNumVO);
            if(-1==result){
                //原提数记录不存在
                return setResult(Constants.RAIS_NUM_ERRO_1, localeMessage.getMessage("tishu.raisnum.error.itemNotFind"), null);
            }
            if(-2==result){
                //延时提数时预计开始时间超过了当前时间
                return setResult(Constants.RAIS_NUM_ERRO_2, localeMessage.getMessage("tishu.raisnum.error.beginTimeOvertime"), null);
            }
            if(-3==result){
                //调用提数脚本调用失败
                return setResult(Constants.RAIS_NUM_ERRO_3, localeMessage.getMessage("tishu.raisnum.error.execRaisShellErro"), null);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/editRaisNum");
            log.setParamStr(JsonUtil.toJsonObjectString(raiseNumVO));
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess(raiseNumVO);
    }
    @ApiOperation(value="物理删除提数记录", notes="物理删除提数记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "提数记录id", required = true, dataType = "String"),
    })
    @RequestMapping(value="deleteRaisNum", method=RequestMethod.POST)
    public ResponseBase deleteRaisNum(String id, HttpServletRequest request){
        try {
            raisNumService.deleteRaisNum(id);
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/deleteRaisNum");
            log.setParamStr("id:"+id);
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess();
    }
    @ApiOperation(value="逻辑删除提数记录", notes="逻辑删除提数记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "提数记录id", required = true, dataType = "String"),
    })
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    @RequestMapping(value="deleteRaisNum_logic", method=RequestMethod.POST)
    public ResponseBase deleteRaisNum_logic(String id, HttpServletRequest request){
        try {
            raisNumService.deleteRaisNum_logic(id);
        } catch (RuntimeException e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/deleteRaisNum_logic");
            log.setParamStr("id:"+id);
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess();
    }


    @ApiOperation(value="查询历史授权记录", notes="查询历史授权记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "5", required = false, dataType = "int"),
    })
    @RequestMapping(value="getReciivetBylimit", method=RequestMethod.GET)
    public ResponseBase getReciivetBylimit(@RequestParam("limit") int limit, HttpServletRequest request){
        List<RaiseNum> raiseNumList = null;
        try {
            Page<Object> pageInfo = PageHelper.startPage(1, limit, false);
            raiseNumList =raisNumService.getReciivetBylimit();
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/getReciivetBylimit");
            log.setParamStr("limit:"+limit);
            log.setReqType(0);//GET
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
        }
        return setResultSuccess(raiseNumList);
    }

    @ApiOperation(value="提数结果回调接口", notes="提数结果回调接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "state", value = "5", required = true, dataType = "String"),
            @ApiImplicitParam(name = "raisNumId", value = "5", required = true, dataType = "String")
    })
    @RequestMapping(value="execRaisShellBack", method=RequestMethod.GET)
    public ResponseBase execRaisShellBack(@RequestParam("state") String state, @RequestParam("raisNumId") String raisNumId,@RequestParam("logId") String logId,HttpServletRequest request){
        try {
           Integer result= raisNumService.execRaisShellBack(state,raisNumId,logId);
            switch (result){
                case -2:
                    return setResultError("提数脚本执行失败");
                case -3:
                    return setResultError("推送Bi系统建表失败");
                case -4:
                    return setResultError("推送bi系统授权用户失败");
                default:
                    return setResultSuccess("执行成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/getReciivetBylimit");
            log.setParamStr("state:"+state);
            log.setReqType(0);//GET
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
        }
    }
    @ApiOperation(value="同步BI相关接口", notes="同步BI相关接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "raisNumId", value = "5", required = true, dataType = "String")
    })
    @RequestMapping(value="pushBi", method=RequestMethod.GET)
    public ResponseBase pushBi( @RequestParam("raisNumId") String raisNumId,HttpServletRequest request){
        try {
            Integer result= raisNumService.execRaisShellBack(Constants.HTTP_RES_CODE_200_VALUE,raisNumId,null);
            switch (result){
                case -3:
                    return setResultError("推送Bi系统建表失败");
                case -4:
                    return setResultError("推送bi系统授权用户失败");
                default:
                    return setResultSuccess("执行成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/pushBi");
            log.setParamStr("raisNumId:"+raisNumId);
            log.setReqType(0);//GET
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
        }
    }
    @ApiOperation(value="查询域账号列表", notes="查询域账号列表")
    @RequestMapping(value="/findLdapUserList", method=RequestMethod.POST)
    public ResponseBase findLdapUserList(@Valid @RequestBody LdapUser ldapUser, BindingResult bindingResult ){
        List<LdapUser> ldapUsers =null;
        try {
            ldapUsers =raisNumService.findLdapUserList(ldapUser.getCn());
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/findLdapUserList");
            log.setParamStr(JsonUtil.toJsonObjectString(ldapUser));
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
        }
        return setResultSuccess(ldapUsers);
    }

    @ApiOperation(value="终止提数", notes="终止提数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "提数记录id", required = true, dataType = "String"),
    })
    @RequestMapping(value="execStopRaisShell", method=RequestMethod.GET)
    public ResponseBase execStopRaisShell(String id, HttpServletRequest request){
        try {
          Integer result= raisNumService.execStopRaisShell(id);
          if(result==1){
              return setResultSuccess();
          }else if(result==-9){
              return setResultError("所选条目并非执行中状态不能终止提数,请刷新页面");
          }else if(result==-3){
              return setResultError("调用终止提数脚本失败，请求没有接收到返回结果");
          }else {
              return setResultError("执行终止提数脚本失败，返回错误码:"+request);
          }
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/execStopRaisShell");
            log.setParamStr("id:"+id);
            log.setReqType(0);//get
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
    }
    @ApiOperation(value="更新提数开始时间", notes="物理删除提数记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "提数记录id", required = true, dataType = "String"),
    })
    @RequestMapping(value="updateBeginTime", method=RequestMethod.POST)
    public ResponseBase updateBeginTime(String id, HttpServletRequest request){
        try {
            raisNumService.updateBeginTime(id);
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.setServerId(TandataServerEnum.Five.getServerId());//tandata-tishuussiness
            log.setUrl(log.getServerId()+"/tishu/RaiseNum/updateBeginTime");
            log.setParamStr("id:"+id);
            log.setReqType(1);//post
            log.setDesribe(baos.toString());
            sysFeignService.insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess();
    }


    @ApiOperation(value = "测试延时提数定时任务", notes = "测试延时提数定时任务")
    @RequestMapping(value = "execRaisNumShell", method = RequestMethod.GET)
    public ResponseBase meterFileAuthoraze() {
        raisNumService.execRaisNumShell();
        return setResultSuccess();
    }
    @ApiOperation(value = "测试清除过期表定时任务", notes = "测试清除过期表定时任务")
    @RequestMapping(value = "execCleanTableShell", method = RequestMethod.GET)
    public ResponseBase execCleanTableShell() {
        raisNumService.execCleanTableShell();
        return setResultSuccess();
    }
}
